import React from "react";
import { useNavigate } from "react-router-dom";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input } from "antd";
import "./login.css";

const Login = () => {
  const navigate = useNavigate();

  const onFinish = (values) => {
    // 拿到登录的所有信息
    console.log("Received values of form: ", values);

    // 模拟用户身份和密码验证
    const users = {
      admin: "admin",
      maintainer: "maintainer",
      logger: "logger",
    };

    const role = users[values.username];
    const password = users[values.username];

    if (role && values.password === password) {
      // 重设时间格式
      const date = new Date();
      const options = {
        year: "numeric",
        month: "short",
        day: "numeric",
        weekday: "short",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
      };
      const result = date.toLocaleString("zh-CN", options);
      const loginInLog = result;

      // 生成登入记录
      console.log(result);

      // 从localStorage中取出登入记录数组
      let loginRecords =
        JSON.parse(window.localStorage.getItem("loginRecords")) || [];
      // 将新的登入记录添加到数组中
      loginRecords.push({ user: role, time: loginInLog });
      // 将登入记录数组转换成字符串存入localStorage
      window.localStorage.setItem("loginRecords", JSON.stringify(loginRecords));

      navigate("/home", { state: { role } });
    } else {
      // 如果用户名或密码错误，提示用户
      alert("用户名或密码错误");
    }
  };

  return (
    <Form
      name="normal_login"
      className="login-form"
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: "请输入用户名！",
          },
        ]}
      >
        <Input
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="用户名"
        />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: "请输入密码！",
          },
        ]}
      >
        <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="密码"
        />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" className="login-form-button">
          登录
        </Button>
      </Form.Item>
      <div className="upHeader">
        <div className="loginWord">登录</div>
      </div>
    </Form>
  );
};

export default Login;
